package com.century.sjt;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.EMChat.activity.ChatActivity;
import com.century.sjt.EMChat.activity.VideoCallActivity;
import com.century.sjt.EMChat.activity.VoiceCallActivity;
import com.century.sjt.activity.MainActivity;
import com.century.sjt.EMChat.domain.Translate;
import com.century.sjt.util.BaiduTranslate;
import com.century.sjt.util.TipUtil;
import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMGroupChangeListener;
import com.easemob.EMNotifierEvent;
import com.easemob.EMValueCallBack;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMMessage.Type;
import com.easemob.chat.TextMessageBody;
import com.century.sjt.EMChat.controller.EaseUI;
import com.century.sjt.EMChat.controller.EaseUI.EaseEmojiconInfoProvider;
import com.century.sjt.EMChat.controller.EaseUI.EaseSettingsProvider;
import com.century.sjt.EMChat.controller.EaseUI.EaseUserProfileProvider;
import com.century.sjt.EMChat.domain.EaseEmojicon;
import com.century.sjt.EMChat.domain.EaseEmojiconGroupEntity;
import com.century.sjt.EMChat.domain.EaseUser;
import com.century.sjt.EMChat.model.EaseNotifier;
import com.century.sjt.EMChat.model.EaseNotifier.EaseNotificationInfoProvider;
import com.century.sjt.EMChat.utils.EaseCommonUtils;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.EMLog;
import com.century.sjt.EMChat.db.DemoDBManager;
import com.century.sjt.EMChat.db.InviteMessgeDao;
import com.century.sjt.EMChat.db.UserDao;
import com.century.sjt.domain.EmojiconExampleGroupData;
import com.century.sjt.domain.InviteMessage;
import com.century.sjt.domain.InviteMessage.InviteMesageStatus;
import com.century.sjt.domain.RobotUser;
import com.century.sjt.receiver.CallReceiver;
import com.century.sjt.utils.PreferenceManager;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class SjtHelper {


    /**
     * 数据同步listener
     */
    static public interface DataSyncListener {
        /**
         * 同步完毕
         *
         * @param success true：成功同步到数据，false失败
         */
        public void onSyncComplete(boolean success);
    }

    protected static final String TAG = "SjtHelper";

    private EaseUI easeUI;

    /**
     * EMEventListener
     */
    protected EMEventListener eventListener = null;

    private Map<String, EaseUser> contactList;

    private Map<String, RobotUser> robotList;

    private static SjtHelper instance = null;

    private SjtModel sjtModel = null;

    /**
     * HuanXin sync groups status listener
     */
    private List<DataSyncListener> syncGroupsListeners;
    /**
     * HuanXin sync contacts status listener
     */
    private List<DataSyncListener> syncContactsListeners;
    /**
     * HuanXin sync blacklist status listener
     */
    private List<DataSyncListener> syncBlackListListeners;

    private boolean isSyncingGroupsWithServer = false;
    private boolean isSyncingContactsWithServer = false;
    private boolean isSynGetContactsWithServer = false;//fals：向后抬获取列表完毕
    private boolean isSyncingBlackListWithServer = false;
    private boolean isGroupsSyncedWithServer = false;
    private boolean isContactsSyncedWithServer = false;
    private boolean isBlackListSyncedWithServer = false;

    /**
     * 百度翻译事件监听
     */
    private BaiduTranslate baiduTranslate;
    //翻译监听
    private TranslateListItemClickListener listener;

    //
    private boolean alreadyNotified = false;

    public boolean isVoiceCalling;
    public boolean isVideoCalling;

    private String username;
    private String mobile;

    private Context appContext;

    private CallReceiver callReceiver;

    private EMConnectionListener connectionListener;

    private InviteMessgeDao inviteMessgeDao;
    private UserDao userDao;

    private LocalBroadcastManager broadcastManager;

    private boolean isGroupAndContactListenerRegisted;

    private RequestQueue mQueue;

    private EaseUser myEaseUser;

    private SjtHelper() {
    }

    public synchronized static SjtHelper getInstance() {
        if (instance == null) {
            instance = new SjtHelper();
        }
        return instance;
    }

    /**
     * init helper
     *
     * @param context application context
     */
    public void init(Context context) {
        if (EaseUI.getInstance().init(context)) {
            appContext = context;
            //设为调试模式，打成正式包时，最好设为false，以免消耗额外的资源
            mQueue = Volley.newRequestQueue(appContext);
            EMChat.getInstance().setDebugMode(false);
            //get easeui instance
            easeUI = EaseUI.getInstance();
            //调用easeui的api设置providers
            setEaseUIProviders();
            sjtModel = new SjtModel(context);
            //设置chat options
            setChatoptions();
            //初始化PreferenceManager
            PreferenceManager.init(context);
            //初始化用户管理类
//            getUserProfileManager().init(context);

            //设置全局监听
            setGlobalListeners();
            broadcastManager = LocalBroadcastManager.getInstance(appContext);
            initDbDao();
        }
    }

    private void setChatoptions() {
        //easeui库默认设置了一些options，可以覆盖
        EMChatOptions options = EMChatManager.getInstance().getChatOptions();
        options.allowChatroomOwnerLeave(getModel().isChatroomOwnerLeaveAllowed());
    }

    protected void setEaseUIProviders() {
        //需要easeui库显示用户头像和昵称设置此provider
        easeUI.setUserProfileProvider(new EaseUserProfileProvider() {

            @Override
            public EaseUser getUser(String username) {
                SharedPreferences mainSharedPreferences = SjtApplication.getInstance().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String userId1 = mainSharedPreferences.getString("userId", "");
//                Log.e("user1",username);
                if (username.equals(userId1)) {
                    return getMyEaseUser();
                }
                return getUserInfo(username);
            }
        });

        //不设置，则使用easeui默认的
        easeUI.setSettingsProvider(new EaseSettingsProvider() {

            @Override
            public boolean isSpeakerOpened() {
                return sjtModel.getSettingMsgSpeaker();
            }

            @Override
            public boolean isMsgVibrateAllowed(EMMessage message) {
                return sjtModel.getSettingMsgVibrate();
            }

            @Override
            public boolean isMsgSoundAllowed(EMMessage message) {
                return sjtModel.getSettingMsgSound();
            }

            @Override
            public boolean isMsgNotifyAllowed(EMMessage message) {
                if (message == null) {
                    return sjtModel.getSettingMsgNotification();
                }
                if (!sjtModel.getSettingMsgNotification()) {
                    return false;
                } else {
                    //如果允许新消息提示
                    //屏蔽的用户和群组不提示用户
                    String chatUsename = null;
                    List<String> notNotifyIds = null;
                    // 获取设置的不提示新消息的用户或者群组ids
                    if (message.getChatType() == ChatType.Chat) {
                        chatUsename = message.getFrom();
                        notNotifyIds = sjtModel.getDisabledIds();
                    } else {
                        chatUsename = message.getTo();
                        notNotifyIds = sjtModel.getDisabledGroups();
                    }

                    if (notNotifyIds == null || !notNotifyIds.contains(chatUsename)) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        });
        //设置表情provider
        easeUI.setEmojiconInfoProvider(new EaseEmojiconInfoProvider() {

            @Override
            public EaseEmojicon getEmojiconInfo(String emojiconIdentityCode) {
                EaseEmojiconGroupEntity data = EmojiconExampleGroupData.getData();
                for (EaseEmojicon emojicon : data.getEmojiconList()) {
                    if (emojicon.getIdentityCode().equals(emojiconIdentityCode)) {
                        return emojicon;
                    }
                }
                return null;
            }

            @Override
            public Map<String, Object> getTextEmojiconMapping() {
                //返回文字表情emoji文本和图片(resource id或者本地路径)的映射map
                return null;
            }
        });

        //不设置，则使用easeui默认的
        easeUI.getNotifier().setNotificationInfoProvider(new EaseNotificationInfoProvider() {

            @Override
            public String getTitle(EMMessage message) {
                //修改标题,这里使用默认
                return  appContext.getResources().getString(R.string.app_name);
            }

            @Override
            public int getSmallIcon(EMMessage message) {
                //设置小图标，这里为默认
                return 0;
            }

            @Override
            public String getDisplayedText(EMMessage message) {
                // 设置状态栏的消息提示，可以根据message的类型做相应提示
                String ticker = EaseCommonUtils.getMessageDigest(message, appContext);
                if (message.getType() == Type.TXT) {
                    ticker = ticker.replaceAll("\\[.{2,3}\\]", "[表情]");
                }
                EaseUser user = getUserInfo(message.getFrom());
//                Log.e("msg",message.getFrom());
                if (user != null) {
                    if (getUserInfo(message.getFrom()).getNick() == null||"".equals(getUserInfo(message.getFrom()).getNick())) {
                        PackageManager packageManager = appContext.getPackageManager();
                        String appname = (String) packageManager.getApplicationLabel(appContext.getApplicationInfo());
                        return appname + ": " + ticker;
                    }
                    else
                        return getUserInfo(message.getFrom()).getNick() + ": " + ticker;

                } else {
                    return message.getFrom() + ": " + ticker;
                }
            }

            @Override
            public String getLatestText(EMMessage message, int fromUsersNum, int messageNum) {
                return null;
                // return fromUsersNum + "个基友，发来了" + messageNum + "条消息";
            }

            @Override
            public Intent getLaunchIntent(EMMessage message) {
                //设置点击通知栏跳转事件
                Intent intent = new Intent(appContext, ChatActivity.class);
                //有电话时优先跳转到通话页面
                if (isVideoCalling) {
                    intent = new Intent(appContext, VideoCallActivity.class);
                } else if (isVoiceCalling) {
                    intent = new Intent(appContext, VoiceCallActivity.class);
                } else {
                    ChatType chatType = message.getChatType();
                    if (chatType == ChatType.Chat) { // 单聊信息
                        intent.putExtra("userId", message.getFrom());
                        intent.putExtra("chatType", Constant.CHATTYPE_SINGLE);
                    } else { // 群聊信息
//                         message.getTo()为群聊id
                        intent.putExtra("userId", message.getTo());
                        if (chatType == ChatType.GroupChat) {
                            intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
                        } else {
                            intent.putExtra("chatType", Constant.CHATTYPE_CHATROOM);
                        }

                    }
                }
                return intent;
            }
        });
    }

    /**
     * 设置全局事件监听
     */
    protected void setGlobalListeners() {
        syncGroupsListeners = new ArrayList<DataSyncListener>();
        syncContactsListeners = new ArrayList<DataSyncListener>();
        syncBlackListListeners = new ArrayList<DataSyncListener>();

        isGroupsSyncedWithServer = sjtModel.isGroupsSynced();
        isContactsSyncedWithServer = sjtModel.isContactSynced();
        isBlackListSyncedWithServer = sjtModel.isBacklistSynced();

        // create the global connection listener

        //实现ConnectionListener接口
        connectionListener = new EMConnectionListener() {
            @Override
            public void onDisconnected(int error) {
                if (error == EMError.USER_REMOVED) {
                    onCurrentAccountRemoved();
                } else if (error == EMError.CONNECTION_CONFLICT) {
                    onConnectionConflict();
                }
            }

            @Override
            public void onConnected() {
                //联系人同步（环信后台）
                // in case group and contact were already synced, we supposed to notify sdk we are ready to receive the events
                if (isGroupsSyncedWithServer && isContactsSyncedWithServer) {
                    new Thread() {
                        @Override
                        public void run() {
                            SjtHelper.getInstance().notifyForRecevingEvents();
                        }
                    }.start();
                } else {
                    if (!isGroupsSyncedWithServer) {
                        asyncFetchGroupsFromServer(null);
                    }

                    if (!isContactsSyncedWithServer) {
                        asyncFetchContactsFromServer(null);
                    }

                    if (!isBlackListSyncedWithServer) {
                        asyncFetchBlackListFromServer(null);
                    }
                }
            }
        };


        IntentFilter callFilter = new IntentFilter(EMChatManager.getInstance().getIncomingCallBroadcastAction());
        if (callReceiver == null) {
            callReceiver = new CallReceiver();
        }

        //注册通话广播接收者
        appContext.registerReceiver(callReceiver, callFilter);
        //注册连接监听
        EMChatManager.getInstance().addConnectionListener(connectionListener);
        //注册群组和联系人监听
        registerGroupAndContactListener();
        //注册消息事件监听
        registerEventListener();
        //注册百度翻译监听
        MyBaiduTranslate();

    }
    //初始化数据库
    private void initDbDao() {
        inviteMessgeDao = new InviteMessgeDao(appContext);
        userDao = new UserDao(appContext);
    }

    /**
     * 注册群组和联系人监听，由于logout的时候会被sdk清除掉，再次登录的时候需要再注册一下
     */
    public void registerGroupAndContactListener() {
        if (!isGroupAndContactListenerRegisted) {
            //注册群组变动监听
            EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener());
            //注册联系人变动监听
            EMContactManager.getInstance().setContactListener(new MyContactListener());
            isGroupAndContactListenerRegisted = true;
        }

    }

    /**
     * 群组变动监听
     */
    class MyGroupChangeListener implements EMGroupChangeListener {

        @Override
        public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {

            boolean hasGroup = false;
            for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            String st3 = appContext.getString(R.string.Invite_you_to_join_a_group_chat);
            EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
            msg.setChatType(ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(inviter + " " + st3));
            // 保存邀请消息
            EMChatManager.getInstance().saveMessage(msg);
            // 提醒新消息
            getNotifier().viberateAndPlayTone(msg);
            //发送local广播
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_GROUP_CHANAGED));
        }

        @Override
        public void onInvitationAccpted(String groupId, String inviter, String reason) {
        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee, String reason) {
        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            //TODO 提示用户被T了，demo省略此步骤
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_GROUP_CHANAGED));
        }

        @Override
        public void onGroupDestroy(String groupId, String groupName) {
            // 群被解散
            //TODO 提示用户群被解散,demo省略
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_GROUP_CHANAGED));
        }

        @Override
        public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) {

            // 用户申请加入群聊
            InviteMessage msg = new InviteMessage();
            msg.setFrom(applyer);
            msg.setTime(System.currentTimeMillis());
            msg.setGroupId(groupId);
            msg.setGroupName(groupName);
            msg.setReason(reason);
            Log.d(TAG, applyer + " 申请加入群聊：" + groupName);
            msg.setStatus(InviteMesageStatus.BEAPPLYED);
            notifyNewIviteMessage(msg);
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_GROUP_CHANAGED));
        }

        @Override
        public void onApplicationAccept(String groupId, String groupName, String accepter) {

            String st4 = appContext.getString(R.string.Agreed_to_your_group_chat_application);
            // 加群申请被同意
            EMMessage msg = EMMessage.createReceiveMessage(Type.TXT);
            msg.setChatType(ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(accepter + " " + st4));
            // 保存同意消息
            EMChatManager.getInstance().saveMessage(msg);
            // 提醒新消息
            getNotifier().viberateAndPlayTone(msg);
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_GROUP_CHANAGED));
        }

        @Override
        public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) {
            // 加群申请被拒绝，demo未实现
        }
    }

    /**
     * 好友变化listener
     */
    public class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(List<String> usernameList) {
            // 保存增加的联系人
            Map<String, EaseUser> localUsers = getContactList();
            Map<String, EaseUser> toAddUsers = new HashMap<String, EaseUser>();
            for (String username : usernameList) {
                EaseUser user = new EaseUser(username);
                // 添加好友时可能会回调added方法两次
                if (!localUsers.containsKey(username)) {
                    userDao.saveContact(user);
                }
                toAddUsers.put(username, user);

            }
            localUsers.putAll(toAddUsers);

            //发送好友变动广播
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANAGED));
        }

        @Override
        public void onContactDeleted(final List<String> usernameList) {
            // 被删除
            Map<String, EaseUser> localUsers = SjtHelper.getInstance().getContactList();
            for (String username : usernameList) {
                localUsers.remove(username);
                userDao.deleteContact(username);
                inviteMessgeDao.deleteMessage(username);
            }
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANAGED));
        }

        @Override
        public void onContactInvited(String username, String reason) {
            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();

            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null && inviteMessage.getFrom().equals(username)) {
                    inviteMessgeDao.deleteMessage(username);
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setReason(reason);
            Log.d(TAG, username + "请求加你为好友,reason: " + reason);
            // 设置相应status
            msg.setStatus(InviteMesageStatus.BEINVITEED);
            notifyNewIviteMessage(msg);
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANAGED));
        }
        //好友同意
        @Override
        public void onContactAgreed(String username) {
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            Log.d(TAG, username + "同意了你的好友请求");
            msg.setStatus(InviteMesageStatus.BEAGREED);
            notifyNewIviteMessage(msg);
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANAGED));
        }

        @Override
        public void onContactRefused(String username) {
            // 参考同意，被邀请实现此功能,demo未实现
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            Log.d(TAG, username + "拒绝了你的好友请求");
            msg.setStatus(InviteMesageStatus.BEREFUSED);
            notifyNewIviteMessage(msg);
            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANAGED));
        }

    }

    /**
     * 保存并提示消息的邀请消息
     *
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        if (inviteMessgeDao == null) {
            inviteMessgeDao = new InviteMessgeDao(appContext);
        }
        inviteMessgeDao.saveMessage(msg);
        //保存未读数，这里没有精确计算
        inviteMessgeDao.saveUnreadMessageCount(1);
        // 提示有新消息
        getNotifier().viberateAndPlayTone(null);
    }

    /**
     * 账号在别的设备登录
     */
    protected void onConnectionConflict() {
        Intent intent = new Intent(appContext, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constant.ACCOUNT_CONFLICT, true);
        appContext.startActivity(intent);
    }

    /**
     * 账号被移除
     */
    protected void onCurrentAccountRemoved() {
        Intent intent = new Intent(appContext, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constant.ACCOUNT_REMOVED, true);
        appContext.startActivity(intent);
    }

    private EaseUser getUserInfo(final String username) {
        //获取user信息，demo是从内存的好友列表里获取，
        //实际开发中，可能还需要从服务器获取用户信息,
        //从服务器获取的数据，最好缓存起来，避免频繁的网络请求
//        Log.e("ErrUserName",username);
        EaseUser user = null;
        user = getContactList().get(username);


        //TODO 获取不在好友列表里的群成员具体信息，即陌生人信息，demo未实现
//        SharedPreferences mainSharedPreferences = appContext.getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
//        String userId = mainSharedPreferences.getString("userId", "");
//        if (username.equals(userId)) {
//            user = getMyEaseUser();
////            GetMyEaseData();
//        }

        return user;
    }
    //获取好友列表上的用户
    public EaseUser getUser(final String username){
        EaseUser user = null;
        user = getContactList().get(username);
        return user;
    }


    //设置当前用户对象
    public EaseUser getMyEaseUser() {
        return myEaseUser;
    }

    public void setMyEaseUser(EaseUser myEaseUser) {
        this.myEaseUser = myEaseUser;
    }

    /**
     * 全局事件监听
     * 因为可能会有UI页面先处理到这个消息，所以一般如果UI页面已经处理，这里就不需要再次处理
     * activityList.size() <= 0 意味着所有页面都已经在后台运行，或者已经离开Activity Stack
     */
    protected void registerEventListener() {//消息监听
        eventListener = new EMEventListener() {
            private BroadcastReceiver broadCastReceiver = null;

            @Override
            public void onEvent(EMNotifierEvent event) {
                EMMessage message = null;
                if (event.getData() instanceof EMMessage) {
                    message = (EMMessage) event.getData();
                    EMLog.d(TAG, "receive the event : " + event.getEvent() + ",id : " + message.getMsgId()+"to"+message.getTo());
                }
//                Log.e("message",message.getBody().toString());

                switch (event.getEvent()) {
                    case EventNewMessage:
                        //应用在后台，不需要刷新UI,通知栏提示新消息
                        if (!easeUI.hasForegroundActivies()) {
                            getNotifier().onNewMsg(message);
                            int type = message.getType().ordinal();
                            if (sjtModel.getSettingBaiTranslate()){
                                if (type == EMMessage.Type.TXT.ordinal()){
                                    String Username = getCurrentUsernName();
                                    SharedPreferences mainSharedPreferences = appContext.getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                                    String languageCode = PreferenceManager.getInstance().getLanguageCode();
                                    if (languageCode.equals(message.getStringAttribute("languageCode",null))){

                                    }else {
                                        if (message.getTo().equals(Username)){
                                            baiduTranslate.translate(appContext,mQueue,message, "zh", "en");
                                        }
                                    }

                                }
                            }
                        }
                        break;
                    case EventOfflineMessage://接收离线消息
                        if (!easeUI.hasForegroundActivies()) {
                            EMLog.d(TAG, "received offline messages");
                            List<EMMessage> messages = (List<EMMessage>) event.getData();
                            getNotifier().onNewMesg(messages);
                        }
                        break;
                    // below is just giving a example to show a cmd toast, the app should not follow this
                    // so be careful of this
                    case EventNewCMDMessage: {
                        EMLog.d(TAG, "收到透传消息");
                        //获取消息body
                        CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
                        final String action = cmdMsgBody.action;//获取自定义action

                        //处理透传消息
                        if ("delFriend".equals(action) || "addFriend".equals(action)) {
                            //删除好友，刷新通讯录
                            isSyncingContactsWithServer = false;
                            asyncFetchContactsFromServer(null);
                        }

                        //获取扩展属性 此处省略
                        //message.getStringAttribute("");
                        EMLog.d(TAG, String.format("透传消息：action:%s,message:%s", action, message.toString()));
                        final String str = appContext.getString(R.string.receive_the_passthrough);

                        final String CMD_TOAST_BROADCAST = "easemob.demo.cmd.toast";
                        IntentFilter cmdFilter = new IntentFilter(CMD_TOAST_BROADCAST);

                        if (broadCastReceiver == null) {
                            broadCastReceiver = new BroadcastReceiver() {

                                @Override
                                public void onReceive(Context context, Intent intent) {
                                    // TODO Auto-generated method stub
//                                Toast.makeText(appContext, intent.getStringExtra("cmd_value"), Toast.LENGTH_SHORT).show();
                                }
                            };

                            //注册广播接收者
                            appContext.registerReceiver(broadCastReceiver, cmdFilter);
                        }

                        Intent broadcastIntent = new Intent(CMD_TOAST_BROADCAST);
                        broadcastIntent.putExtra("cmd_value", str + action);
                        appContext.sendBroadcast(broadcastIntent, null);

                        break;
                    }
                    case EventDeliveryAck:
                        message.setDelivered(true);
                        break;
                    case EventReadAck:
                        message.setAcked(true);
                        break;
                    // add other events in case you are interested in
                    default:
                        break;
                }

            }
        };

        EMChatManager.getInstance().registerEventListener(eventListener);
    }

    /**
     * 是否登录成功过
     *
     * @return
     */
    public boolean isLoggedIn() {
        return EMChat.getInstance().isLoggedIn();
    }

    /**
     * 退出登录
     *
     * @param unbindDeviceToken 是否解绑设备token(使用GCM才有)
     * @param callback          callback
     */
    public void logout(boolean unbindDeviceToken, final EMCallBack callback) {
        endCall();
        EMChatManager.getInstance().logout(unbindDeviceToken, new EMCallBack() {

            @Override
            public void onSuccess() {
                reset();
                if (callback != null) {
                    callback.onSuccess();
                }

            }

            @Override
            public void onProgress(int progress, String status) {
                if (callback != null) {
                    callback.onProgress(progress, status);
                }
            }

            @Override
            public void onError(int code, String error) {
                if (callback != null) {
                    callback.onError(code, error);
                }
            }
        });
    }

    /**
     * 获取消息通知类
     *
     * @return
     */
    public EaseNotifier getNotifier() {
        return easeUI.getNotifier();
    }

    public SjtModel getModel() {
        return (SjtModel) sjtModel;
    }

    /**
     * 设置好友user list到内存中
     *
     * @param contactList
     */
    public void setContactList(Map<String, EaseUser> contactList) {
        this.contactList = contactList;
    }

    /**
     * 保存单个user
     */
    public void saveContact(EaseUser user) {
        contactList.put(user.getUsername(), user);
        sjtModel.saveContact(user);
    }

    /**
     * 获取好友list
     *
     * @return
     */
    public Map<String, EaseUser> getContactList() {
//        updateMyContactList();
        if (isLoggedIn() && contactList == null) {
            contactList = sjtModel.getContactList();
        }

        return contactList;
    }

    /**
     * 获取当前用户的环信id
     */
    public String getCurrentUsernName() {
        if (username == null) {
            SharedPreferences mainSharedPreferences = appContext.getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
            String userId = mainSharedPreferences.getString("userId", "");
//            username = sjtModel.getCurrentUsernName();
            username = userId;
        }
        return username;
    }

    /**
     * 获取当前用户的环信id
     */
    public String getCurrentMobile() {
        if (mobile == null) {
            SharedPreferences mainSharedPreferences = appContext.getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
            String userId = mainSharedPreferences.getString("userId", "");
            String phone = mainSharedPreferences.getString("mobile","");
//            mobile = sjtModel.getCurrentMobile();
            mobile = phone;
        }
        return mobile;
    }

    public void setRobotList(Map<String, RobotUser> robotList) {
        this.robotList = robotList;
    }

    public Map<String, RobotUser> getRobotList() {
        if (isLoggedIn() && robotList == null) {
            robotList = sjtModel.getRobotList();
        }
        return robotList;
    }

    /**
     * 更新用户列表缓存和数据库
     *
     * @param contactList
     */
    public void updateContactList(List<EaseUser> contactInfoList) {
        for (EaseUser u : contactInfoList) {
            contactList.put(u.getUsername(), u);
        }
        ArrayList<EaseUser> mList = new ArrayList<EaseUser>();
        mList.addAll(contactList.values());
        sjtModel.saveContactList(mList);
    }

    /**
     * 更新单个新用户数据
     * @return
     */
    public void updateUser(EaseUser user){
        if (user!=null){
            contactList.put(user.getUsername(),user);
            sjtModel.saveContact(user);
        }
    }

    /**
     * 删除好友
     * @return
     */
    public void delectUser(EaseUser user){
        if (user !=null){
            contactList.remove(user);
        }
    }
    //中断通话
    void endCall() {
        try {
            EMChatManager.getInstance().endCall();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//    //添加到环信群组同步
//    public void addSyncGroupListener(DataSyncListener listener) {
//        if (listener == null) {
//            return;
//        }
//        if (!syncGroupsListeners.contains(listener)) {
//            syncGroupsListeners.add(listener);
//        }
//    }
//    //移除掉环信群组同步
//    public void removeSyncGroupListener(DataSyncListener listener) {
//        if (listener == null) {
//            return;
//        }
//        if (syncGroupsListeners.contains(listener)) {
//            syncGroupsListeners.remove(listener);
//        }
//    }
//    //添加环信好友同步
//    public void addSyncContactListener(DataSyncListener listener) {
//        if (listener == null) {
//            return;
//        }
//        if (!syncContactsListeners.contains(listener)) {
//            syncContactsListeners.add(listener);
//        }
//    }
//    //移除环信好友同步
//    public void removeSyncContactListener(DataSyncListener listener) {
//        if (listener == null) {
//            return;
//        }
//        if (syncContactsListeners.contains(listener)) {
//            syncContactsListeners.remove(listener);
//        }
//    }
//    //同步加入黑名单
//    public void addSyncBlackListListener(DataSyncListener listener) {
//        if (listener == null) {
//            return;
//        }
//        if (!syncBlackListListeners.contains(listener)) {
//            syncBlackListListeners.add(listener);
//        }
//    }
//    //移除黑名单
//    public void removeSyncBlackListListener(DataSyncListener listener) {
//        if (listener == null) {
//            return;
//        }
//        if (syncBlackListListeners.contains(listener)) {
//            syncBlackListListeners.remove(listener);
//        }
//    }

    /**
     * 同步操作，从服务器获取群组列表
     * 该方法会记录更新状态，可以通过isSyncingGroupsFromServer获取是否正在更新
     * 和isGroupsSyncedWithServer获取是否更新已经完成
     *
     * @throws EaseMobException
     */
    public synchronized void asyncFetchGroupsFromServer(final EMCallBack callback) {
        if (isSyncingGroupsWithServer) {
            return;
        }

        isSyncingGroupsWithServer = true;

        new Thread() {
            @Override
            public void run() {
                try {
                    EMGroupManager.getInstance().getGroupsFromServer();

                    // in case that logout already before server returns, we should return immediately
                    if (!EMChat.getInstance().isLoggedIn()) {
                        return;
                    }

                    sjtModel.setGroupsSynced(true);

                    isGroupsSyncedWithServer = true;
                    isSyncingGroupsWithServer = false;

                    //通知listener同步群组完毕
                    noitifyGroupSyncListeners(true);
                    if (isContactsSyncedWithServer()) {
                        notifyForRecevingEvents();
                    }
                    if (callback != null) {
                        callback.onSuccess();
                    }
                } catch (EaseMobException e) {
                    sjtModel.setGroupsSynced(false);
                    isGroupsSyncedWithServer = false;
                    isSyncingGroupsWithServer = false;
                    noitifyGroupSyncListeners(false);
                    if (callback != null) {
                        callback.onError(e.getErrorCode(), e.toString());
                    }
                }

            }
        }.start();
    }
    //群组同步监听
    public void noitifyGroupSyncListeners(boolean success) {
        for (DataSyncListener listener : syncGroupsListeners) {
            listener.onSyncComplete(success);
        }
    }
    //刷新好友列表
    public  void updateFetchContacts() {
        isSyncingContactsWithServer = false;
        isSynGetContactsWithServer = true;//向后台获取列表
        asyncFetchContactsFromServer(null);
    }
    //获取好友列表
    public void asyncFetchContactsFromServer(final EMValueCallBack<List<String>> callback) {
        if (isSyncingContactsWithServer) {
            return;
        }

        isSyncingContactsWithServer = true;

        new Thread() {
            @Override
            public void run() {
                final List<String> usernames = new ArrayList<String>();
                final Map<String, EaseUser> userlist = new HashMap<String, EaseUser>();
//               try {
//                   usernames=Getusernames(callback);

                StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.GetFriendList, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            TipUtil.closeProgressDialog();
                            TipUtil.log("获取好友列表", response.toString(), 1);
                            JSONTokener jsonParser = new JSONTokener(response);
                            JSONObject res = (JSONObject) jsonParser.nextValue();
                            String code = res.getString("code");
                            String message = res.getString("message");
                            JSONObject Data = res.getJSONObject("data");
                            if (code.equals("200")) {//成功
                                JSONArray friendList = Data.getJSONArray("friendList");
                                for (int i = 0; i < friendList.length(); i++) {
                                    JSONObject aData = (JSONObject) friendList.get(i);
                                    String userId = aData.getString("userId");
                                    String nick = aData.getString("nickName");
                                    String initialLetter = aData.getString("initialLetter");
                                    String mobile = aData.getString("mobile");
                                    String imageId = aData.getString("imageId");
                                    String imageUrl = aData.getString("imageUrl");
                                    EaseUser user = new EaseUser(userId);
                                    user.setNick(nick);
                                    user.setMobile(mobile);
                                    user.setInitialLetter(initialLetter);
                                    user.setAvatarid(imageId);
                                    user.setAvatar(imageUrl);
                                    user.setIsShop("0");
                                    EaseCommonUtils.setUserInitialLetter(user);

                                    userlist.put(userId, user);
//                                           usernames.add(userId);
                                    usernames.add(i, userId);

                                }
                                JSONArray friendIsShopList=Data.getJSONArray("friendIsShopList");
                                for (int i = 0; i < friendIsShopList.length(); i++) {
                                    JSONObject aData = (JSONObject) friendIsShopList.get(i);
                                    String userId = aData.getString("userId");
                                    String nick = aData.getString("nickName");
                                    String initialLetter = aData.getString("initialLetter");
                                    String mobile = aData.getString("mobile");
                                    String imageId = aData.getString("imageId");
                                    String imageUrl = aData.getString("imageUrl");
                                    String ShopId = aData.getString("shopId");
                                    EaseUser user = new EaseUser(userId);
                                    user.setNick(nick);
                                    user.setMobile(mobile);
                                    user.setInitialLetter(initialLetter);
                                    user.setAvatarid(imageId);
                                    user.setAvatar(imageUrl);
                                    user.setShopId(ShopId);
                                    user.setIsShop("1");
                                    EaseCommonUtils.setUserInitialLetter(user);

                                    userlist.put(userId, user);
//                                           usernames.add(userId);
                                    usernames.add(i, userId);

                                }
                                getContactList().clear();
                                getContactList().putAll(userlist);
                                // 存入db
                                UserDao dao = new UserDao(appContext);
                                List<EaseUser> users = new ArrayList<EaseUser>(userlist.values());
                                dao.saveContactList(users);
                                isSynGetContactsWithServer = false;//后台获取列表成功

                                sjtModel.saveContactList(users);
                                EMLog.d(TAG, "set contact syn status to true");
                                isContactsSyncedWithServer = true;
                                isSyncingContactsWithServer = false;
                                //parse获取用户信息，换成sjt服务器获取
                                updateContactList(users);
                                //通知listeners联系人同步完毕
                                notifyContactsSyncListener(true);
                                GetMyEaseData();
                                if (isGroupsSyncedWithServer()) {
                                    notifyForRecevingEvents();
                                }
                            } else {//失败
                                TipUtil.log(message, response.toString(), 1);
                                sjtModel.setContactSynced(false);
//
                            }

//                                   getUserProfileManager().asyncFetchContactInfosFromServer(usernames,new EMValueCallBack<List<EaseUser>>() {
//
//                                       @Override
//                                       public void onSuccess(List<EaseUser> uList) {
//                                              updateContactList(users);
//                                              getUserProfileManager().notifyContactInfosSyncListener(true);
//                                       }
//
//                                       @Override
//                                       public void onError(int error, String errorMsg) {
//                                       }
//                                   });
                            if (callback != null) {
                                callback.onSuccess(usernames);
                            }
                        } catch (Exception ex) {
                            sjtModel.setContactSynced(false);
                            isContactsSyncedWithServer = false;
                            isSyncingContactsWithServer = false;
                            noitifyGroupSyncListeners(false);
                            isSynGetContactsWithServer=false;

                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
//                TipUtil.log(appContext.getResources().getString(R.string.error_network),response.toString() , 1);
//                TipUtil.closeProgressDialog();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<String, String>();
                        SharedPreferences mainSharedPreferences = appContext.getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                        String userId = mainSharedPreferences.getString("userId", "");
                        map.put("loginId", userId);

                        return map;
                    }

                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        SharedPreferences mainSharedPreferences = appContext.getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                        String cookie = mainSharedPreferences.getString("cookie", "");
                        String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                        HashMap localHashMap = new HashMap();
                        String cookieValue = cookie + ";" + rememberMeValue;
                        localHashMap.put("Cookie", cookieValue);
                        return localHashMap;
                    }
                };
                mQueue.add(stringRequest);


//
//                   //获取用户列表
//                   usernames = EMContactManager.getInstance().getContactUserNames();
//                   // in case that logout already before server returns, we should return immediately
//                   if(!EMChat.getInstance().isLoggedIn()){
//                       return;
//                   }
//                   Map<String, EaseUser> userlist = new HashMap<String, EaseUser>();
//                   for (String username : usernames) {
//                       EaseUser user = new EaseUser(username);
//                       EaseCommonUtils.setUserInitialLetter(user);
//                       userlist.put(username, user);
//                   }
//                   Map<String, EaseUser> userlist = new HashMap<String, EaseUser>();
//                   userlist=Getusernames(callback);
//                   // 存入内存
//                   getContactList().clear();
//                   getContactList().putAll(userlist);
//                    // 存入db
//                   UserDao dao = new UserDao(appContext);
//                   List<EaseUser> users = new ArrayList<EaseUser>(userlist.values());
//                   dao.saveContactList(users);

//                   sjtModel.setContactSynced(true);
////                   EMLog.d(TAG, "set contact syn status to true");
//
//                   isContactsSyncedWithServer = true;
//                   isSyncingContactsWithServer = false;
//
//                   //通知listeners联系人同步完毕
//                   notifyContactsSyncListener(true);
//                   if(isGroupsSyncedWithServer()){
//                       notifyForRecevingEvents();
//                   }


//                   getUserProfileManager().asyncFetchContactInfosFromServer(usernames,new EMValueCallBack<List<EaseUser>>() {
//
//                       @Override
//                       public void onSuccess(List<EaseUser> uList) {
//                           updateContactList(uList);
//                           getUserProfileManager().notifyContactInfosSyncListener(true);
//                       }
//
//                       @Override
//                       public void onError(int error, String errorMsg) {
//                       }
//                   });
//                   if(callback != null){
//                       callback.onSuccess(usernames);
//                   }
//               } catch (Exception ex){
//                   sjtModel.setContactSynced(false);
//                   isContactsSyncedWithServer = false;
//                   isSyncingContactsWithServer = false;
//                   noitifyGroupSyncListeners(false);
//
////                   if(callback != null){
////                       callback.onError(ex.getErrorCode(), e.toString());
////                   }
//                   ex.printStackTrace();
//               }
//
            }
        }.start();
    }

    //获得黑名单
    public void notifyContactsSyncListener(boolean success) {
        for (DataSyncListener listener : syncContactsListeners) {
            listener.onSyncComplete(success);
        }
    }

    public void asyncFetchBlackListFromServer(final EMValueCallBack<List<String>> callback) {

        if (isSyncingBlackListWithServer) {
            return;
        }

        isSyncingBlackListWithServer = true;

        new Thread() {
            @Override
            public void run() {
                try {
                    List<String> usernames = EMContactManager.getInstance().getBlackListUsernamesFromServer();
                    // in case that logout already before server returns, we should return immediately
                    if (!EMChat.getInstance().isLoggedIn()) {
                        return;
                    }

                    sjtModel.setBlacklistSynced(true);
                    isBlackListSyncedWithServer = true;
                    isSyncingBlackListWithServer = false;

                    EMContactManager.getInstance().saveBlackList(usernames);
                    notifyBlackListSyncListener(true);
                    if (callback != null) {
                        callback.onSuccess(usernames);
                    }
                } catch (EaseMobException e) {
                    sjtModel.setBlacklistSynced(false);

                    isBlackListSyncedWithServer = false;
                    isSyncingBlackListWithServer = true;
                    e.printStackTrace();

                    if (callback != null) {
                        callback.onError(e.getErrorCode(), e.toString());
                    }
                }

            }
        }.start();
    }
    //黑名单没有变更
    public void notifyBlackListSyncListener(boolean success) {
        for (DataSyncListener listener : syncBlackListListeners) {
            listener.onSyncComplete(success);
        }
    }

    public boolean isSyncingGroupsWithServer() {
        return isSyncingGroupsWithServer;
    }

    public boolean isSyncingContactsWithServer() {
        return isSyncingContactsWithServer;
    }

    public void setSyncingContactsWithServer(boolean isSyncingContactsWithServer) {
        this.isSyncingContactsWithServer = isSyncingContactsWithServer;
    }

    public boolean isSyncingBlackListWithServer() {
        return isSyncingBlackListWithServer;
    }

    public boolean isGroupsSyncedWithServer() {
        return isGroupsSyncedWithServer;
    }

    public boolean isContactsSyncedWithServer() {
        return isContactsSyncedWithServer;
    }

    public boolean isBlackListSyncedWithServer() {
        return isBlackListSyncedWithServer;
    }

    public synchronized void notifyForRecevingEvents() {
        if (alreadyNotified) {
            return;
        }

        // 通知sdk，UI 已经初始化完毕，注册了相应的receiver和listener, 可以接受broadcast了
        EMChat.getInstance().setAppInited();
        alreadyNotified = true;
    }

    synchronized void reset() {
        isSyncingGroupsWithServer = false;
        isSyncingContactsWithServer = false;
        isSyncingBlackListWithServer = false;

        sjtModel.setGroupsSynced(false);
        sjtModel.setContactSynced(false);
        sjtModel.setBlacklistSynced(false);

        isGroupsSyncedWithServer = false;
        isContactsSyncedWithServer = false;
        isBlackListSyncedWithServer = false;

        alreadyNotified = false;
        isGroupAndContactListenerRegisted = false;

        setContactList(null);
        setRobotList(null);
        DemoDBManager.getInstance().closeDB();
    }

    public void pushActivity(Activity activity) {
        easeUI.pushActivity(activity);
    }

    public void popActivity(Activity activity) {
        easeUI.popActivity(activity);
    }

    /**
     * 百度翻译
     */

    public void MyBaiduTranslate(){
        baiduTranslate = new BaiduTranslate();
        baiduTranslate.setTranslateListItemClickListener(new BaiduTranslate.TranslateListItemClickListener() {
            @Override
            public void onSaveClick(Translate message) {
                listener.onSaveClick(message);
            }

            @Override
            public void onUpdateClick(Translate message) {
            }

            @Override
            public void onDeleteClick(Translate message) {
            }
        });
    }

    /**
     * 获取用户信息
     */
    public void GetMyEaseData() {
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), MerchantActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.GetOneFriendData, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取个人信息", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject aData = res.getJSONObject("data");

                    if (code.equals("200")) {//成功
                        String userId = aData.getString("userId");
                        String nick = aData.getString("nickName");
                        String initialLetter = aData.getString("nickInitialLetter");
                        String mobile = aData.getString("mobile");
                        String imageId = aData.getString("image");
                        String imageUrl = aData.getString("imageUrl");
                        EaseUser user = new EaseUser(userId);
                        user.setNick(nick);
                        user.setMobile(mobile);
                        user.setAvatarid(imageId);
                        user.setAvatar(imageUrl);
                        user.setInitialLetter(initialLetter);
                        SjtHelper.getInstance().setMyEaseUser(user);
//                        getContactList().clear();
//                        getContactList().putAll(userlist);
//                        getContactList().put(userId,user);
//                         存入db
//                        UserDao dao = new UserDao(appContext);
//                        List<EaseUser> users = new ArrayList<EaseUser>(userlist.values());
//                        dao.saveContactList(users);
//                        dao.saveContact(user);
//                        userDao.saveContact(user);
                    } else {//失败
                        TipUtil.log(message, response.toString(), 1);
//                        sjtModel.setContactSynced(false);
//
                    }

//                    return Response.success(userlist, HttpHeaderParser.parseCacheHeaders(response));
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.log(appContext.getResources().getString(R.string.error_service), response.toString(), 1);

                }

            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                TipUtil.log(appContext.getResources().getString(R.string.error_network),response.toString() , 1);
//                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = appContext.getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("userId", userId);

                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = appContext.getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };

        mQueue.add(stringRequest);

    }

    public void setTranslateListItemClickListener(TranslateListItemClickListener listener) {
        this.listener = listener;
    }
    public interface TranslateListItemClickListener{
        /**
         * 翻译事件监听
         * @param message
         * @return
         */
        void onSaveClick(Translate message);
    }

}
